/*
@Copyright:LintCode
@Author:   tjyemail
@Problem:  http://www.lintcode.com/problem/unique-binary-search-trees-ii
@Language: C++
@Datetime: 16-02-09 08:49
*/

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    vector<TreeNode*> build(int start,int end){
        vector<TreeNode*> vs;
        if (start>end){
            vs.push_back(NULL);
            return vs;
        }
        if (start==end){
            vs.push_back(new TreeNode(start));
            return vs;
        }
        for(int i=start;i<=end;++i){
            vector<TreeNode*> lefts = build(start,i-1);
            vector<TreeNode*> rights = build(i+1,end);
            for(int l=0;l<lefts.size();++l)
                for(int r=0;r<rights.size();++r){
                    TreeNode *h = new TreeNode(i);
                    h->left = lefts[l];
                    h->right = rights[r];
                    vs.push_back(h);
                }
        }
        return vs;
    }
public:
    /**
     * @paramn n: An integer
     * @return: A list of root
     */
    vector<TreeNode *> generateTrees(int n) {
        // write your code here
        return build(1,n);
    }
};